#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.
#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import application, cis, command, compatibleunit, geography, oms, staker, unsorted
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
import _mysql as mysql


def GetEmptyStringForNull(String):
    if(not String):
        return ''
    else:
        return String


#Temporary home of SymbologyAdjustLine, figure out with code refactoring version where to put
def SymbologyAdjustLine(Line, CircuitNumber):
    Station1=geography.Station.objects.filter(Point__distance_lte=(Point(Line[0][0], Line[0][1], djangoproject.settings.COOPGISSRID), 1 * djangoproject.settings.COOPGISDistanceMultiplier))[0]
    Circuits1=Station1.GetCircuitNumbers()

    Station2=geography.Station.objects.filter(Point__distance_lte=(Point(Line[1][0], Line[1][1], djangoproject.settings.COOPGISSRID), 1 * djangoproject.settings.COOPGISDistanceMultiplier))[0]
    Circuits2=Station2.GetCircuitNumbers()

    for i in Circuits1:
        if(i in [9999]):
            
            return LineString([Station1.Point.coords, Station2.Point.coords], srid=djangoproject.settings.COOPGISSRID)#Do not adjust for substation/special circuits
    for i in Circuits2:
        if(i in [9999]):

            return LineString([Station1.Point.coords, Station2.Point.coords], srid=djangoproject.settings.COOPGISSRID)#Do not adjust for substation/special circuits#Do not adjust for substation/special circuits

    Point1=list(Station1.Point.coords)
    if(len(Circuits1) > 1 and not compatibleunit.Assembly.objects.filter(CompatibleUnit__SubstationIndicator=True).exclude(BypassIndicator=True).filter(Station=Station1)):
        if(CircuitNumber == Circuits1[0]):
            Point1[1] = Point1[1] + 0.75 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber == Circuits1[1]):
            Point1[1] = Point1[1] + 0.5 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber == Circuits1[2]):
            Point1[1] = Point1[1] + 0.25 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber==Circuits1[3]):
            Point1[1] = Point1[1] - 0.25 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber==Circuits1[4]):
            Point1[1] = Point1[1] - 0.5 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber==Circuits1[5]):
            Point1[1] = Point1[1] - 0.75 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber==Circuits1[6]):
            Point1[1] = Point1[1] - 1 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber==Circuits1[7]):
            Point1[1] = Point1[1] - 1.25 * djangoproject.settings.COOPGISDistanceMultiplier
        else:
            Point1[1] = Point1[1] + 0 * djangoproject.settings.COOPGISDistanceMultiplier

    
    Point2=list(Station2.Point.coords)
    if(len(Circuits2) > 1 and not compatibleunit.Assembly.objects.filter(CompatibleUnit__SubstationIndicator=True).exclude(BypassIndicator=True).filter(Station=Station2)):
        if(CircuitNumber == Circuits2[0]):
            Point2[1] = Point2[1] + 0.75 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber == Circuits2[1]):
            Point2[1] = Point2[1] + 0.5 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber == Circuits2[2]):
            Point2[1] = Point2[1] + 0.25 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber==Circuits2[3]):
            Point2[1] = Point2[1] - 0.25 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber==Circuits2[4]):
            Point2[1] = Point2[1] - 0.5 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber==Circuits2[5]):
            Point2[1] = Point2[1] - 0.75 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber==Circuits2[6]):
            Point2[1] = Point2[1] - 1 * djangoproject.settings.COOPGISDistanceMultiplier
        elif(CircuitNumber==Circuits2[7]):
            Point2[1] = Point2[1] - 1.25 * djangoproject.settings.COOPGISDistanceMultiplier
        else:
            Point2[1] = Point2[1] + 0 * djangoproject.settings.COOPGISDistanceMultiplier
    return LineString([Point1, Point2], srid=djangoproject.settings.COOPGISSRID)

#Temporary home of SymbologyAdjustPoint, figure out with code refactoring where to put
def SymbologyAdjustPoint(point, CircuitNumber):
    Station1=geography.Station.objects.filter(Point=point)[0]
    Circuits1=Station1.GetCircuitNumbers()
    Point1=list(Station1.Point.coords)
    for i in Circuits1:
        if(i in [9999]):            
            return Point(Point1, srid=djangoproject.settings.COOPGISSRID)#Do not adjust for substation/special circuits
    try:
        if(len(Circuits1) > 1 and not compatibleunit.Assembly.objects.filter(CompatibleUnit__SubstationIndicator=True).exclude(BypassIndicator=True).filter(Station=Station1)):
            if(CircuitNumber == Circuits1[0]):
                Point1[1] = Point1[1] + 0.75
            elif(CircuitNumber == Circuits1[1]):
                Point1[1] = Point1[1] + 0.5 
            elif(CircuitNumber == Circuits1[2]):
                Point1[1] = Point1[1] + 0.25
            elif(CircuitNumber==Circuits1[3]):
                Point1[1] = Point1[1] - 0.25
            elif(CircuitNumber==Circuits1[4]):
                Point1[1] = Point1[1] - 0.5
            elif(CircuitNumber==Circuits1[5]):
                Point1[1] = Point1[1] - 0.75
            elif(CircuitNumber==Circuits1[6]):
                Point1[1] = Point1[1] - 1
            elif(CircuitNumber==Circuits1[7]):
                Point1[1] = Point1[1] - 1.25
            else:
                Point1[1] = Point1[1] + 0
    except:
        pass
    return Point(Point1, srid=djangoproject.settings.COOPGISSRID)


#Temporary home of CalculateInBetweenPoint until code refactoring
def CalculateInBetweenPoint(Point1, Point2, PercentofPoint1=0.9):
    PercentofPoint2 = 1 - PercentofPoint1
    PointFinalX = (PercentofPoint1 * Point1.x) + (PercentofPoint2 * Point2.x)
    PointFinalY = (PercentofPoint1 * Point1.y) + (PercentofPoint2 * Point2.y)
    return Point(PointFinalX, PointFinalY, srid=djangoproject.settings.COOPGISSRID)


#Temporary home of SplitLine until code refactoring 
def SplitLine(line, point):
    LineCoords1=line.coords[0]
    LineCoords2=line.coords[1]
    PointCoords=point.coords
    MinimumDistance=0.25 * djangoproject.settings.COOPGISDistanceMultiplier  #Do not split lines into segments smaller than this value
    Distance1=pow( pow(LineCoords1[0] - PointCoords[0], 2) + pow(LineCoords1[1] - PointCoords[1], 2), 0.5 * djangoproject.settings.COOPGISDistanceMultiplier)
    Distance2=pow( pow(LineCoords2[0] - PointCoords[0], 2) + pow(LineCoords2[1] - PointCoords[1], 2), 0.5 * djangoproject.settings.COOPGISDistanceMultiplier)
    if(Distance1 < MinimumDistance or Distance2 < MinimumDistance):
        return [line]  #This also avoids splitting lines that are already split, since one of the distances will be zero or close...
    Line1=LineString(LineCoords1, PointCoords, srid=djangoproject.settings.COOPGISSRID)
    Line2=LineString(LineCoords2, PointCoords, srid=djangoproject.settings.COOPGISSRID)
    return [Line1, Line2]

def SymbologyAddToPhaseCode(PhaseCode, PhaseAIndicator, PhaseBIndicator, PhaseCIndicator):
    if(PhaseAIndicator):
        if(not 'A' in PhaseCode):
            PhaseCode = 'A' + PhaseCode
    if(PhaseBIndicator):
       if(not 'B' in PhaseCode):
           PhaseCode = 'B' + PhaseCode
    if(PhaseCIndicator):
        if(not 'C' in PhaseCode):
            PhaseCode = PhaseCode + 'C'
    if(PhaseCode == 'BAC'):
        PhaseCode='ABC'
    elif(PhaseCode == 'BA'):
        PhaseCode = 'AB'
    return PhaseCode    

class SymbologyProtectedSpan(models.Model):
    """Protected Spans are those that are protected by an Assembly in the ProtectingAssembly model"""
    Line=models.LineStringField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    SpanNumberAsText=models.CharField(db_column='spannumberastext', max_length=250)
    Span=models.ForeignKey('Span', db_column='span_id')
    OpenIndicatorAsText=models.CharField(db_column='openindicatorastext',max_length=250) #"True" if open, "False" if closed, "Both" if open from one side and closed from another
    ProtectingAssemblies=models.TextField(db_column='protectingassemblies',) #ID of all Protecting Assemblies for this span, separated by commas
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyprotectedspan'
        app_label='djangoproject'
    def BuildSymbology(self, span=None):
        if(span):
            SymbologyProtectedSpan.objects.filter(Span=span).delete()
            Spans=[span]
        else:
            SymbologyProtectedSpan.objects.all().delete()
            Spans=geography.Span.objects.all()
        for i in Spans:
            ProtectingAssemblies=compatibleunit.ProtectingAssembly.objects.filter(Span=i)
            StatusesFound=[]
            for protectingAssembly in ProtectingAssemblies:
                if(not protectingAssembly.Assembly.OpenIndicator in StatusesFound):
                    StatusesFound.append(protectingAssembly.Assembly.OpenIndicator)
            if(StatusesFound):
                if(len(StatusesFound) > 1):
                    OpenIndicatorAsText='Both'
                elif(StatusesFound[0] == False):
                    OpenIndicatorAsText='False'
                else:
                    OpenIndicatorAsText='True'
            else:
                OpenIndicatorAsText='None, indicates an error in SymbologyProtectedSpan model if shown as a value in the db'
            for protectingassembly in ProtectingAssemblies:
                if(SymbologyProtectedSpan.objects.filter(Span=i)):
                    CurrentProtectedSpan = SymbologyProtectedSpan.objects.filter(Span=i)[0]
                    CurrentProtectedSpan.ProtectingAssemblies=CurrentProtectedSpan.ProtectingAssemblies + ', ' + str(protectingAssembly.id)
                    CurrentProtectedSpan.OpenIndicatorAsText=OpenIndicatorAsText
                    CurrentProtectedSpan.save()
                else:
                    CurrentProtectedSpan=SymbologyProtectedSpan()
                    CurrentProtectedSpan.Span=i
                    CurrentProtectedSpan.Line=i.Line
                    CurrentProtectedSpan.SpanNumberAsText=str(i.id)
                    CurrentProtectedSpan.ProtectingAssemblies=str(protectingassembly.id)
                    CurrentProtectedSpan.OpenIndicatorAsText=OpenIndicatorAsText
                    CurrentProtectedSpan.save()

class SymbologyCutOut(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    PhaseCode=models.TextField(db_column='phasecode')
    CompatibleUnit=models.TextField(db_column='compatibleunit')
    FuseAmpRating=models.TextField(db_column='fuseamprating')
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    Assembly=models.ForeignKey('Assembly', db_column='assembly_id')
    TagNumber=models.TextField(db_column='tagnumber')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologycutout'
        app_label='djangoproject'
    def GetCutOutPhaseCodes(self, station, ProtectedSpans):
        CutOuts=compatibleunit.Assembly.objects.filter(Station=station).filter(CompatibleUnit__CutOutIndicator=True).exclude(BypassIndicator=True).exclude(InstallStatus__Name='Install')
        TempPhaseCode=[]
        for i in CutOuts:
            if(ProtectedSpans):
                CutOutProtectedSpans=compatibleunit.ProtectingAssembly.objects.filter(Assembly=i)
                for span in CutOutProtectedSpans:
                    for span2 in ProtectedSpans:
                        if span.Span == span2.Span:
                            TempPhaseCode.append(i.GetPhaseCode())
            else:
                TempPhaseCode.append(i.GetPhaseCode())
        TempPhaseCodeString=''.join(TempPhaseCode)
        PhaseCodeString=''
        if('A' in TempPhaseCodeString):
            PhaseCodeString=PhaseCodeString + 'A'
        if('B' in TempPhaseCodeString):
            PhaseCodeString=PhaseCodeString + 'B'
        if('C' in TempPhaseCodeString):
            PhaseCodeString=PhaseCodeString + 'C'
        return PhaseCodeString
    def BuildSymbology(self, station=None):
        from django.contrib.gis.db import models
        if(station):
            SymbologyCutOut.objects.filter(Station=station).delete()
            CutOuts=compatibleunit.Assembly.objects.filter(CompatibleUnit__CutOutIndicator=True, Station=station).exclude(BypassIndicator=True).exclude(InstallStatus__Name='Install').exclude(TransformerCutOutIndicator=True)
        else:
            SymbologyCutOut.objects.all().delete()
            CutOuts=compatibleunit.Assembly.objects.filter(CompatibleUnit__CutOutIndicator=True).exclude(BypassIndicator=True).exclude(InstallStatus__Name='Install').exclude(TransformerCutOutIndicator=True)
        for i in CutOuts:
            ProtectedSpans=compatibleunit.ProtectingAssembly.objects.filter(Assembly=i)
            if(not ProtectedSpans):
                New=SymbologyCutOut()
                New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
                New.PhaseCode=self.GetCutOutPhaseCodes(i.Station, ProtectedSpans)
                New.CompatibleUnit=GetEmptyStringForNull(str(i.CompatibleUnit))
                New.CircuitNumber=GetEmptyStringForNull(i.CircuitNumber)
                New.Station=GetEmptyStringForNull(i.Station)
                New.Assembly=GetEmptyStringForNull(i)
                New.FuseAmpRating='Unknown'
                New.TagNumber=i.GetNearestTagNumber()
                New.save()
            for protectedspan in ProtectedSpans:  #for each protected span, put a copy of the symbologycutoutpoint 10% down that span
                New=SymbologyCutOut()
                Point1=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
                Point2=SymbologyAdjustPoint(protectedspan.Span.FarStation(i.Station).Point, i.CircuitNumber)
                New.Point=CalculateInBetweenPoint(Point1, Point2)
                #New.PhaseCode=GetEmptyStringForNull(i.GetPhaseCode())
                New.PhaseCode=self.GetCutOutPhaseCodes(i.Station, ProtectedSpans)
                New.CompatibleUnit=GetEmptyStringForNull(str(i.CompatibleUnit))
                New.CircuitNumber=GetEmptyStringForNull(i.CircuitNumber)
                New.Station=i.Station
                New.Assembly=GetEmptyStringForNull(i)
                New.FuseAmpRating='Unknown'
                New.TagNumber=i.GetNearestTagNumber()
                New.save()
                #Now, split up any PrimaryLine and SecondaryLine Symbologies affected by this point
                PrimaryLineSymbologies=SymbologyPrimaryLine.objects.filter(Span=protectedspan.Span).filter(CircuitNumber=New.CircuitNumber)
                for primaryLineSymbology in PrimaryLineSymbologies:
                    NewLines=SplitLine(primaryLineSymbology.Line, New.Point)
                    for newLine in NewLines:
                        primaryLineSymbology.CreateCopy(newLine)
                    primaryLineSymbology.delete()
                SecondaryLineSymbologies=SymbologySecondaryLine.objects.filter(Span=protectedspan.Span).filter(CircuitNumber=New.CircuitNumber)
                for secondaryLineSymbology in SecondaryLineSymbologies:
                    NewLines=SplitLine(secondaryLineSymbology.Line, New.Point)
                    for newLine in NewLines:
                        secondaryLineSymbology.CreateCopy(newLine)
                    secondaryLineSymbology.delete()

class SymbologyFeeder(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Rotation=models.FloatField(db_column='rotation')
    PhaseCode=models.TextField(db_column='phasecode')
    CompatibleUnit=models.TextField(db_column='compatibleunit') 
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    OMSCircuitNumber=models.TextField(db_column='omscircuitnumber')
    OMSSubstationNumber=models.TextField(db_column='omssubstationnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    TagNumber=models.TextField(db_column='tagnumber')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyfeeder'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        from django.contrib.gis.db import models
        if(station):
            SymbologyFeeder.objects.filter(Station=station).delete()
            Feeders=compatibleunit.Assembly.objects.filter(CompatibleUnit__FeederIndicator=True, Station=station).exclude(BypassIndicator=True).exclude(InstallStatus__Name='Install')
        else:
            SymbologyFeeder.objects.all().delete()
            Feeders=compatibleunit.Assembly.objects.filter(CompatibleUnit__FeederIndicator=True).exclude(BypassIndicator=True).exclude(InstallStatus__Name='Install')
        for i in Feeders:
            New=SymbologyFeeder()
            New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
            New.PhaseCode=i.GetPhaseCode()
            New.CompatibleUnit=str(i.CompatibleUnit)
            New.CircuitNumber=i.CircuitNumber
            try:
                New.OMSCircuitNumber=oms.OMSCircuitMap.objects.filter(GISCircuitNumber=str(i.CircuitNumber))[0].OMSCircuitNumber
            except:
                New.OMSCircuitNumber=''

            Spans1=geography.Span.objects.filter(StartStation=i.Station)
            Spans2=geography.Span.objects.filter(EndStation=i.Station)
            Spans=[]
            for span in Spans1:
                Spans.append(span)
            for span in Spans2:
                Spans.append(span)
            for span in Spans:
                try:
                    substation=compatibleunit.Assembly.objects.filter(CompatibleUnit__SubstationIndicator=True).exclude(BypassIndicator=True).filter(Station=span.FarStation(i.Station))[0]
                except IndexError:
                    continue
                try:
                    New.OMSSubstationNumber=oms.OMSSubstationMap.objects.filter(GISSubstationNumber=substation.TagNumber)[0].OMSSubstationNumber
                    break
                except IndexError:
                    New.OMSNumber=''
            New.Rotation=i.Rotation
            New.Station=i.Station
            if(i.TagNumber):
                New.TagNumber=i.TagNumber
            else:
                New.TagNumber=''
            New.save()
    
class SymbologyPoleJointUse(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    PoleJointUse=models.TextField(db_column='polejointuse')
    TagNumber=models.TextField(db_column='tagnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyjointuse'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        from django.contrib.gis.db import models
        if(station):
            SymbologyPoleJointUse.objects.filter(Station=station).delete()
            Stations=[station]
        else:
            SymbologyPoleJointUse.objects.all().delete()
            All=compatibleunit.PoleJointUse.objects.all()
            Stations=[]
            for i in All:
                if(not i.Station in Stations):
                    Stations.append(i.Station)
        for i in Stations:
            New=SymbologyPoleJointUse()
            New.Point=i.Point
            PoleJointUseList=[]
            PoleJointUses=compatibleunit.PoleJointUse.objects.filter(Station=i)
            for poleJointUse in PoleJointUses:
                PoleJointUseList.append(str(poleJointUse))
            DictWithQuantity={}
            for string in PoleJointUseList:
                if(string[2:] in DictWithQuantity.keys()):
                    DictWithQuantity[string[2:]]=DictWithQuantity[string[2:]] + 1
                else:
                    DictWithQuantity[string[2:]]=1
            PoleJointUseListWithQuantity=[]
            for key in DictWithQuantity.keys():
                PoleJointUseListWithQuantity.append(str(DictWithQuantity[key]) + ' ' + key)
            New.PoleJointUse=GetEmptyStringForNull('\n'.join(PoleJointUseListWithQuantity))
            New.Station=GetEmptyStringForNull(i)
            if(PoleJointUseList):
                New.save()


class SymbologyPoleTreatment(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    PoleTreatmentTypeName=models.TextField(db_column='poletreatmenttypename')
    PoleTreatmentCompanyName=models.TextField(db_column='polecompanyname')
    PoleTreatmentDate=models.DateField(db_column='poletreatmentdate')
    TagNumber=models.TextField(db_column='tagnumber')
    Year=models.IntegerField(null=True, blank=True, db_column='year')
    Station=models.ForeignKey('Station', db_column='station_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologypoletreatment'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        from django.contrib.gis.db import models
        if(station):
            SymbologyPoleTreatment.objects.filter(Station=station).delete()
            PoleTreatments=compatibleunit.PoleTreatment.objects.filter(Pole__Station=station)
        else:
            SymbologyPoleTreatment.objects.all().delete()
            PoleTreatments=compatibleunit.PoleTreatment.objects.all()
        for i in PoleTreatments:
            Age=datetime.datetime.now() - i.CreateDateTime
            New=SymbologyPoleTreatment()
            New.Point=i.Pole.Station.Point
            New.PoleTreatmentTypeName=GetEmptyStringForNull(i.PoleTreatmentType.Name)
            New.PoleTreatmentCompanyName=GetEmptyStringForNull(i.Company.Name)
            New.PoleTreatmentDate=i.PoleTreatmentDate
            try:
                New.Year=i.PoleTreatmentDate.year
            except:
                New.Year=9999
            New.TagNumber=GetEmptyStringForNull(i.Pole.TagNumber)
            New.Station=i.Pole.Station
            New.save()




class SymbologyLight(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Rotation=models.FloatField(db_column='rotation')
    PhaseCode=models.TextField(db_column='phasecode')
    CompatibleUnit=models.TextField(db_column='compatibleunit') 
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    Station=models.ForeignKey('Station',db_column='station_id')
    TagNumber=models.TextField(db_column='tagnumber')
    MapNumber=models.CharField(max_length=250, db_column='mapnumber')    
    InstallStatusName=models.CharField(max_length=250, db_column='installstatusname') #Lights will display in different colors depending on install status
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologylight'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        from django.contrib.gis.db import models
        if(station):
            SymbologyLight.objects.filter(Station=station).delete()
            Lights=compatibleunit.Assembly.objects.filter(CompatibleUnit__LightIndicator=True, Station=station).exclude(BypassIndicator=True)
        else:
            SymbologyLight.objects.all().delete()
            Lights=compatibleunit.Assembly.objects.filter(CompatibleUnit__LightIndicator=True).exclude(BypassIndicator=True)
        for i in Lights:
            New=SymbologyLight()
            New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
            New.PhaseCode=i.GetPhaseCode()
            New.CompatibleUnit=GetEmptyStringForNull(str(i.CompatibleUnit))
            New.CircuitNumber=i.CircuitNumber
            New.Rotation=i.Rotation
            New.Station=i.Station
            New.MapNumber=GetEmptyStringForNull(i.MapNumber)
            New.InstallStatusName=GetEmptyStringForNull(i.InstallStatus.Name)
            New.TagNumber=i.GetNearestTagNumber()
            New.save()
    
class SymbologyMeter(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    CompatibleUnit=models.TextField(db_column='compatibleunit')
    MeterNumber=models.CharField(max_length=250, db_column='meternumber')
    MeterDCSINumber=models.CharField(max_length=250, db_column='meterdcsinumber')
    OldMapNumber=models.CharField(max_length=250, db_column='oldmapnumber')
    MapNumber=models.TextField(db_column='mapnumber')
    ActiveStatus=models.TextField(db_column='activestatus')
    PhaseCode=models.TextField(db_column='phasecode')
    Station=models.ForeignKey('Station', db_column='station_id')
    MeterForm=models.TextField(db_column='meterform')
    CircuitNumber=models.TextField(db_column='circuitnumber')
    NearbyTagNumber=models.TextField(db_column='nearbytagnumber')
    NearbyMeters=models.TextField(db_column='nearbymeters')  #A List of DCSI Numbers
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologymeter'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        from django.contrib.gis.db import models
        if(station):
            SymbologyMeter.objects.filter(Station=station).delete()
            Meters=compatibleunit.Assembly.objects.filter(CompatibleUnit__MeterIndicator=True, Station=station).exclude(InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologyMeter.objects.all().delete()
            Meters=compatibleunit.Assembly.objects.filter(CompatibleUnit__MeterIndicator=True).exclude(InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in Meters:
            New=SymbologyMeter()
            New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
            New.ActiveStatus=GetEmptyStringForNull(str(i.MeterActiveIndicator))
            New.CompatibleUnit=GetEmptyStringForNull(str(i.CompatibleUnit))
            New.Station=i.Station
            New.MeterNumber=GetEmptyStringForNull(i.MeterNumber)
            New.MeterDCSINumber=GetEmptyStringForNull(i.MeterDCSINumber)
            New.OldMapNumber=GetEmptyStringForNull(i.OldMapNumber)
            New.MapNumber=i.GetLongMapNumber()
            New.CircuitNumber=i.CircuitNumber
            New.PhaseCode = i.GetPhaseCode()
            try:
                New.MeterForm=i.MeterForm.Name
            except:
                New.MeterForm=''
            #New.CalculateNearbyObjects(Save=False)
            New.save()    
    def CalculateNearbyObjects(self, SaveIndicator=True):
        MaxHops=100
        count = 0
        CurrentStation=self.Station
        PotentialSpans=[]
        VisitedStations=[]
        while(count < MaxHops):
            VisitedStations.append(CurrentStation)
            PotentialAssemblies = compatibleunit.Assembly.objects.filter(Station=CurrentStation).exclude(TagNumber='').exclude(BypassIndicator=True)
            if(PotentialAssemblies):
                self.NearbyTagNumber=PotentialAssemblies[0].TagNumber
                break
            count = count + 1
            if(count > MaxHops):
                break
            Spans=geography.Span().GetAllMatching(CurrentStation)
            for span in Spans:
                PotentialSpans.append(span)
            for span in PotentialSpans:
                if(not span.StartStation in VisitedStations):
                    CurrentStation=span.StartStation
                if(not span.EndStation in VisitedStations):
                    CurrentStation=span.EndStation
        """list of 10 nearest meters limited by phase, circuit and a 5 mile maximum distance"""
        Radii=[500,5280,26400] #feet
        MaximumMeters=10
        count=0 
        PotentialMeters=SymbologyMeter.objects.filter(CircuitNumber=self.CircuitNumber).filter(PhaseCode=self.PhaseCode).exclude(MeterDCSINumber=''
                        ).exclude(MeterDCSINumber='0').exclude(MeterDCSINumber__iexact='idle').exclude(Station=self.Station)
        while count < len(Radii):            
            PotentialMeters2=PotentialMeters.filter(Point__distance_lte=(self.Point, Radii[count]))
            if PotentialMeters2.count() >= MaximumMeters:
                break
            count+=1
        NearbyMeterTuples=[]
        for meter in PotentialMeters2.distance(self.Point):
            NearbyMeterTuples.append((meter.distance.ft, meter.MeterDCSINumber))
        NearbyMeterTuples.sort()
        NearbyMeters=[]
        for entry in NearbyMeterTuples[:10]:
            NearbyMeters.append(entry[1])
        self.NearbyMeters=str(NearbyMeters)
        if(SaveIndicator):
            self.save()      

class SymbologyOpenPoint(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Rotation=models.FloatField(db_column='rotation')
    PhaseCode=models.TextField(db_column='phasecode')
    CompatibleUnit=models.TextField(db_column='compatibleunit') 
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    TagNumber=models.TextField(db_column='tagnumber')
    Assembly=models.ForeignKey('Assembly', db_column='assembly_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyopenpoint'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        from django.contrib.gis.db import models
        if(station):
            SymbologyOpenPoint.objects.filter(Station=station).delete()
            OpenPoints=compatibleunit.Assembly.objects.filter(OpenIndicator=True, Station=station).exclude(InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologyOpenPoint.objects.all().delete()
            OpenPoints=compatibleunit.Assembly.objects.filter(OpenIndicator=True).exclude(InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in OpenPoints:
            ProtectedSpans=compatibleunit.ProtectingAssembly.objects.filter(Assembly=i)
            if(not ProtectedSpans):
                New=SymbologyOpenPoint()
                New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
                New.PhaseCode=i.GetPhaseCode()
                New.CompatibleUnit=str(i.CompatibleUnit)
                New.CircuitNumber=i.CircuitNumber
                New.Rotation=i.Rotation
                New.Station=i.Station
                New.Assembly=i
                New.TagNumber=i.GetNearestTagNumber()
                New.save()
            for protectedSpan in ProtectedSpans:  #for each protected span, put a copy of the symbologyopenpoint 10% down that span
                New=SymbologyOpenPoint()
                Point1=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
                Point2=SymbologyAdjustPoint(protectedSpan.Span.FarStation(i.Station).Point, i.CircuitNumber)
                New.Point=CalculateInBetweenPoint(Point1, Point2)
                New.PhaseCode=GetEmptyStringForNull(i.GetPhaseCode())
                New.CompatibleUnit=GetEmptyStringForNull(str(i.CompatibleUnit))
                New.CircuitNumber=i.CircuitNumber
                New.Rotation=i.Rotation
                New.Station=i.Station
                New.TagNumber=i.GetNearestTagNumber()
                New.Assembly=i
                New.save()
                #Now, split up any PrimaryLine and SecondaryLine Symbologies affected by this point
                PrimaryLineSymbologies=SymbologyPrimaryLine.objects.filter(Span=protectedSpan.Span).filter(CircuitNumber=New.CircuitNumber)
                for primaryLineSymbology in PrimaryLineSymbologies:
                    NewLines=SplitLine(primaryLineSymbology.Line, New.Point)
                    for newLine in NewLines:
                        primaryLineSymbology.CreateCopy(newLine)
                    primaryLineSymbology.delete()
                SecondaryLineSymbologies=SymbologySecondaryLine.objects.filter(Span=protectedSpan.Span).filter(CircuitNumber=New.CircuitNumber)
                for secondaryLineSymbology in SecondaryLineSymbologies:
                    NewLines=SplitLine(secondaryLineSymbology.Line, New.Point)
                    for newLine in NewLines:
                        secondaryLineSymbology.CreateCopy(newLine)
                    secondaryLineSymbology.delete()
                  
                    


class SymbologyPrimaryLine(models.Model):
    Line=models.LineStringField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    PhaseCode=models.TextField(db_column='phasecode')
    CompatibleUnits=models.TextField(db_column='compatibleunits') #Storage of Unique Compatible Units
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    Span=models.ForeignKey('Span', db_column='span_id')
    UndergroundIndicator=models.NullBooleanField(null=True, blank=True, db_column='undergroundindicator')  #If False, the Line is OverHead
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyprimaryline'
        app_label='djangoproject'
    def BuildSymbology(self, span=None):
        from django.contrib.gis.db import models
        if(span):
            SymbologyPrimaryLine.objects.filter(Span=span).delete()
            PrimaryLines=compatibleunit.Assembly.objects.filter(CompatibleUnit__ConductorIndicator=True, PrimaryIndicator=True,
                                                       Span=span).exclude(InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologyPrimaryLine.objects.all().delete()
            PrimaryLines=compatibleunit.Assembly.objects.filter(CompatibleUnit__ConductorIndicator=True, 
                                                       PrimaryIndicator=True).exclude(InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in PrimaryLines:
            New=SymbologyPrimaryLine()
            New.Line=SymbologyAdjustLine(i.Span.Line, i.CircuitNumber)
            OldExisting=SymbologyPrimaryLine.objects.filter(Line=New.Line, CircuitNumber=i.CircuitNumber, 
                                                                  UndergroundIndicator=i.UndergroundIndicator)
            if(OldExisting):
                OldExisting=OldExisting[0]
                OldExisting.PhaseCode=SymbologyAddToPhaseCode(str(OldExisting.PhaseCode), i.PhaseAIndicator, i.PhaseBIndicator, i.PhaseCIndicator)
                OldExisting.CompatibleUnits = str(OldExisting.CompatibleUnits) + ', ' + str(i.CompatibleUnit)
                OldExisting.UndergroundIndicator=i.UndergroundIndicator
                OldExisting.save()
            else:
                New.PhaseCode=i.GetPhaseCode()
                New.CompatibleUnits=str(i.CompatibleUnit)
                New.CircuitNumber=i.CircuitNumber
                New.Span=i.Span
                New.UndergroundIndicator=i.UndergroundIndicator
                New.save()
    def CreateCopy(self, NewLine):
        New=SymbologyPrimaryLine()
        New.Line=NewLine
        New.PhaseCode=GetEmptyStringForNull(self.PhaseCode)
        New.CompatibleUnits=GetEmptyStringForNull(self.CompatibleUnits)
        New.CircuitNumber=self.CircuitNumber
        New.Span=self.Span
        New.UndergroundIndicator=self.UndergroundIndicator
        New.save()

class SymbologySecondaryLine(models.Model):
    Line=models.LineStringField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    PhaseCode=models.TextField(db_column='phasecode')
    CompatibleUnits=models.TextField(db_column='compatibleunits') #Storage of Unique Compatible Units
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    Span=models.ForeignKey('Span', db_column='span_id')
    UndergroundIndicator=models.BooleanField(db_column='undergroundindicator')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologysecondaryline'
        app_label='djangoproject'
    def BuildSymbology(self, span=None):
        from django.contrib.gis.db import models
        if(span):
            SymbologySecondaryLine.objects.filter(Span=span).delete()
            SecondaryLines1=compatibleunit.Assembly.objects.filter(CompatibleUnit__ConductorIndicator=True, SecondaryIndicator=True,
                                                          Span=span).exclude(InstallStatus__Name='Install').exclude(BypassIndicator=True)
            SecondaryLines2=compatibleunit.Assembly.objects.filter(CompatibleUnit__ConductorIndicator=True, ServiceIndicator=True,
                                                          Span=span).exclude(InstallStatus__Name='Install').exclude(BypassIndicator=True)  
        else:
            
            SymbologySecondaryLine.objects.all().delete()
            SecondaryLines1=compatibleunit.Assembly.objects.filter(CompatibleUnit__ConductorIndicator=True, 
                                                          SecondaryIndicator=True).exclude(InstallStatus__Name='Install').exclude(BypassIndicator=True)
            SecondaryLines2=compatibleunit.Assembly.objects.filter(CompatibleUnit__ConductorIndicator=True,
                                                          ServiceIndicator=True).exclude(InstallStatus__Name='Install').exclude(BypassIndicator=True)
        SecondaryLines=[]
        for i in SecondaryLines1:
            SecondaryLines.append(i)
        for i in SecondaryLines2:
            SecondaryLines.append(i)  
        for i in SecondaryLines:
            New=SymbologySecondaryLine()
            New.Line=SymbologyAdjustLine(i.Span.Line, i.CircuitNumber)
            OldExisting=SymbologySecondaryLine.objects.filter(Line=New.Line, CircuitNumber=i.CircuitNumber, UndergroundIndicator=i.UndergroundIndicator)
            if(OldExisting):
                OldExisting=OldExisting[0]
                OldExisting.PhaseCode=SymbologyAddToPhaseCode(OldExisting.PhaseCode, i.PhaseAIndicator, i.PhaseBIndicator, i.PhaseCIndicator)
                if(not (str(i.CompatibleUnit) in OldExisting.CompatibleUnits)):
                    OldExisting.CompatibleUnits = str(OldExisting.CompatibleUnits) + '\n' + str(i.CompatibleUnit)
                OldExisting.save()
            else:
                New.PhaseCode=i.GetPhaseCode()
                New.CompatibleUnits=str(i.CompatibleUnit)
                New.CircuitNumber=i.CircuitNumber
                New.Span=i.Span
                New.UndergroundIndicator=i.UndergroundIndicator
                New.save()
    def CreateCopy(self, NewLine):
        New=SymbologySecondaryLine()
        New.Line=NewLine
        New.PhaseCode=self.PhaseCode
        New.CompatibleUnits=self.CompatibleUnits
        New.CircuitNumber=self.CircuitNumber
        New.Span=self.Span
        New.UndergroundIndicator=self.UndergroundIndicator
        New.save()

class SymbologyStakerWorkOrderStation(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Station=models.ForeignKey('Station', db_column='station_id')
    StakerWorkOrder=models.ForeignKey('StakerWorkOrder', db_column='stakerworkorder_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologystakerworkorderstation'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        if(station):
            SymbologyStakerWorkOrderStation.objects.filter(Station=station).delete()
            StationAssemblies=compatibleunit.Assembly.objects.filter(Station=station).exclude(StakerWorkOrder=None).exclude(BypassIndicator=True)
        else:
            SymbologyStakerWorkOrderStation.objects.all().delete()
            StationAssemblies=compatibleunit.Assembly.objects.filter(CompatibleUnit__StationIndicator=True).exclude(StakerWorkOrder=None).exclude(BypassIndicator=True)
        for assembly in StationAssemblies:
            New=SymbologyStakerWorkOrderStation()
            New.Point=assembly.Station.Point
            New.StakerWorkOrder=assembly.StakerWorkOrder
            New.Station=assembly.Station
            New.save()

class SymbologyStakerWorkOrderSpan(models.Model):
    Line=models.LineStringField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Span=models.ForeignKey('Span', db_column='span_id')
    StakerWorkOrder=models.ForeignKey('StakerWorkOrder', db_column='stakerworkorder_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologystakerworkorderspan'
        app_label='djangoproject'
    def BuildSymbology(self, span=None):
        from django.contrib.gis.db import models
        if(span):
            SymbologyStakerWorkOrderSpan.objects.filter(Span=span).delete()
            SpanAssemblies=compatibleunit.Assembly.objects.filter(Span=span).exclude(StakerWorkOrder=None).exclude(BypassIndicator=True)
        else:
            SymbologyStakerWorkOrderSpan.objects.all().delete()
            SpanAssemblies=compatibleunit.Assembly.objects.filter(CompatibleUnit__SpanIndicator=True).exclude(StakerWorkOrder=None).exclude(BypassIndicator=True)
        for assembly in SpanAssemblies:
            New=SymbologyStakerWorkOrderSpan()
            New.Line=assembly.Span.Line
            New.StakerWorkOrder=assembly.StakerWorkOrder
            New.Span=assembly.Span
            New.save()

class SymbologyTransformer(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Rotation=models.FloatField(db_column='rotation')
    PhaseCode=models.TextField(db_column='phasecode')
    CompatibleUnit=models.TextField(db_column='compatibleunit') 
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    TagNumber=models.TextField(db_column='tagnumber')
    UndergroundIndicator=models.BooleanField(db_column='undergroundindicator')
    TagNumber=models.TextField(db_column='tagnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    TransformerBank=models.TextField(db_column='transformerbank')
    TransformerBankid=models.IntegerField(null=True, blank=True, db_column='transformerbankid')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologytransformer'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        if(station):
            SymbologyTransformer.objects.filter(Station=station).delete()
            Transformers=compatibleunit.Assembly.objects.filter(CompatibleUnit__TransformerIndicator=True, Station=station).exclude(
                             InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologyTransformer.objects.all().delete()
            Transformers=compatibleunit.Assembly.objects.filter(CompatibleUnit__TransformerIndicator=True).exclude(
                             InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in Transformers:
            New=SymbologyTransformer()
            New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
            New.PhaseCode=GetEmptyStringForNull(i.GetPhaseCode())
            New.CompatibleUnit=str(i.CompatibleUnit)
            New.CircuitNumber=i.CircuitNumber
            New.Rotation=i.Rotation
            New.Station=i.Station
            New.UndergroundIndicator=i.UndergroundIndicator
            New.TagNumber=GetEmptyStringForNull(i.TagNumber)
            if(i.TransformerBank):
                New.TransformerBank=i.TransformerBank.TransformerBankType.Name
                New.TransformerBankid=i.TransformerBank.id
            else:
                New.TransformerBank=''
                New.TransformerBankid=None
            #if(New.TransformerBank == 'Wye'):   #Temporary code until DataVoice supports Wye Banks
            #    TransformerBankTransformers=djangoproject.models.compatibleunit.Assembly.objects.filter(TransformerBank=djangoproject.models.compatibleunit.TransformerBank.objects.filter(id=New.TransformerBankid))
            #    PhaseString=''
            #    for j in TransformerBankTransformers:
            #        PhaseString = PhaseString + j.GetPhaseCode()
            #    New.PhaseCode = ''
            #    if('A' in PhaseString):
            #        New.PhaseCode = 'A'
            #    if('B' in PhaseString):
            #        New.PhaseCode = New.PhaseCode + 'B'
            #    if('C' in PhaseString):
            #        New.PhaseCode = New.PhaseCode + 'C'

                
            if(not New.TagNumber):
                New.TagNumber=i.GetNearestTagNumber()
            New.save()    

class SymbologyPole(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    CompatibleUnit=models.TextField(db_column='compatibleunit')
    JointUse=models.TextField(db_column='jointuse')
    PoleTreatment=models.TextField(db_column='poletreatment')
    Type=models.TextField(db_column='type')
    TagNumber=models.TextField(db_column='tagnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologypole'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        if(station):
            SymbologyPole.objects.filter(Station=station).delete()
            Poles=compatibleunit.Assembly.objects.filter(CompatibleUnit__PoleIndicator=True, Station=station).exclude(
                      InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologyPole.objects.all().delete()
            Poles=compatibleunit.Assembly.objects.filter(CompatibleUnit__PoleIndicator=True).exclude(
                      InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in Poles:
            New=SymbologyPole()
            New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
            New.CompatibleUnit=str(i.CompatibleUnit)
            PoleJointUseList=[]
            PoleJointUses=compatibleunit.PoleJointUse.objects.filter(Station=i.Station)
            for poleJointUse in PoleJointUses:
                PoleJointUseList.append(str(poleJointUse))
            PoleJointUseString='\n'.join(PoleJointUseList)
            New.JointUse=PoleJointUseString[1:]
            PoleTreatmentList=[]
            PoleTreatments=compatibleunit.PoleTreatment.objects.filter(Pole=i).order_by('-PoleTreatmentDate')
            try:
                New.PoleTreatment=str(PoleTreatments[0].PoleTreatmentDate.year)
            except IndexError:
                pass
            if(i.PrimaryIndicator):
                New.Type='Primary'
            elif(i.PoleLightIndicator):
                New.Type='Light'
            elif(i.PoleStubIndicator):
                New.Type='Stub'
            elif(i.SecondaryIndicator):
                New.Type='Secondary'
            elif(i.PoleGuyIndicator):
                New.Type='Guy'
            else:
                New.Type='Unknown'
            New.TagNumber=GetEmptyStringForNull(str(i.TagNumber))
            New.Station=i.Station
            New.save()
                
class SymbologyNonProtectingAssembly(models.Model):
    """Holds all Assemblies of types that could protect a span but currently do not."""
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Station=models.ForeignKey('Station', db_column='station_id')
    AssemblyNames=models.TextField(db_column='assemblynames')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologynonprotectingassembly'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        if(station):
            SymbologyNonProtectingAssembly.objects.filter(Station=station).delete()
            OpenPoints=compatibleunit.Assembly.objects.filter(Station=station).filter(CompatibleUnit__OpenPointIndicator=True).exclude(BypassIndicator=True)
            CutOuts=compatibleunit.Assembly.objects.filter(Station=station).filter(CompatibleUnit__CutOutIndicator=True).exclude(BypassIndicator=True)
            Reclosers=compatibleunit.Assembly.objects.filter(Station=station).filter(CompatibleUnit__RecloserIndicator=True).exclude(BypassIndicator=True)
            Regulators=compatibleunit.Assembly.objects.filter(Station=station).filter(CompatibleUnit__RegulatorIndicator=True).exclude(BypassIndicator=True)
            Switches=compatibleunit.Assembly.objects.filter(Station=station).filter(CompatibleUnit__SwitchIndicator=True).exclude(BypassIndicator=True)
        else:
            SymbologyNonProtectingAssembly.objects.all().delete()
            OpenPoints=compatibleunit.Assembly.objects.filter(CompatibleUnit__OpenPointIndicator=True).exclude(BypassIndicator=True)
            CutOuts=compatibleunit.Assembly.objects.filter(CompatibleUnit__CutOutIndicator=True).exclude(BypassIndicator=True)
            Reclosers=compatibleunit.Assembly.objects.filter(CompatibleUnit__RecloserIndicator=True).exclude(BypassIndicator=True)
            Regulators=compatibleunit.Assembly.objects.filter(CompatibleUnit__RegulatorIndicator=True).exclude(BypassIndicator=True)
            Switches=compatibleunit.Assembly.objects.filter(CompatibleUnit__SwitchIndicator=True).exclude(BypassIndicator=True)
        Assemblies=[]
        for i in OpenPoints:
            Assemblies.append(i)
        for i in CutOuts:
            Assemblies.append(i)
        for i in Reclosers:
            Assemblies.append(i)
        for i in Regulators:
            Assemblies.append(i)
        for i in Switches:
            Assemblies.append(i)         
        for i in Assemblies:
            New=SymbologyNonProtectingAssembly()
            Existing=SymbologyNonProtectingAssembly.objects.filter(Point=i.Station.Point)
            if(Existing):
                Existing[0].AssemblyNames=str(Existing[0].AssemblyNames) + ', ' + str(i.CompatibleUnit.Name)
                Existing[0].save()
            else:
                New=SymbologyNonProtectingAssembly()
                New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
                New.Station=i.Station
                New.AssemblyNames=str(i.CompatibleUnit.Name)
                New.save()

class SymbologyRecloser(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Rotation=models.FloatField(db_column='rotation')
    PhaseCode=models.TextField(db_column='phasecode')
    CompatibleUnit=models.TextField(db_column='compatibleunit') 
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    TagNumber=models.TextField(db_column='tagnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyrecloser'
        app_label='djangoproject'
    def GetRecloserPhaseCodes(self, station):  #Temporary Code until OMS Upgrade in Spring, 2012, Gregory Roby 1/31/2012, handles multiple single phase reclosers as a single location
        Reclosers=compatibleunit.Assembly.objects.filter(Station=station).filter(CompatibleUnit__RecloserIndicator=True).exclude(
                      InstallStatus__Name='Install').exclude(BypassIndicator=True)
        TempPhaseCode=[]
        for i in Reclosers:
            TempPhaseCode.append(i.GetPhaseCode())
        TempPhaseCodeString=''.join(TempPhaseCode)
        PhaseCodeString=''
        if('A' in TempPhaseCodeString):
            PhaseCodeString=PhaseCodeString + 'A'
        if('B' in TempPhaseCodeString):
            PhaseCodeString=PhaseCodeString + 'B'
        if('C' in TempPhaseCodeString):
            PhaseCodeString=PhaseCodeString + 'C'
        return PhaseCodeString
        
    def BuildSymbology(self, station=None):
        if(station):
            SymbologyRecloser.objects.filter(Station=station).delete()
            Reclosers=compatibleunit.Assembly.objects.filter(CompatibleUnit__RecloserIndicator=True, Station=station).exclude(
                          InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologyRecloser.objects.all().delete()
            Reclosers=compatibleunit.Assembly.objects.filter(CompatibleUnit__RecloserIndicator=True).exclude(
                          InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in Reclosers:
            ProtectedSpans=compatibleunit.ProtectingAssembly.objects.filter(Assembly=i)
            if(not ProtectedSpans):
                New=SymbologyRecloser()
                New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
                #New.PhaseCode=i.GetPhaseCode()  
                New.PhaseCode=self.GetRecloserPhaseCodes(i.Station)  #Gets all phase codes for reclosers at the current station (keep until OMS upgrade 01/31/2012 Gregory Roby)
                New.CompatibleUnit=str(i.CompatibleUnit)
                New.CircuitNumber=i.CircuitNumber
                New.Rotation=i.Rotation
                New.TagNumber=i.GetNearestTagNumber()
                New.Station=i.Station
                New.save()
            for protectedspan in ProtectedSpans:  #for each protected span, put a copy of the symbologyrecloser 10% down that span
                New=SymbologyRecloser()
                Point1=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
                Point2=SymbologyAdjustPoint(protectedspan.Span.FarStation(i.Station).Point, i.CircuitNumber)
                New.Point=CalculateInBetweenPoint(Point1, Point2)
                #New.PhaseCode=GetEmptyStringForNull(i.GetPhaseCode())
                New.PhaseCode=self.GetRecloserPhaseCodes(i.Station)  #Gets all phase codes for reclosers at the current station (keep until OMS upgrade 01/31/2012 Gregory Roby)
                New.CompatibleUnit=GetEmptyStringForNull(str(i.CompatibleUnit))
                New.CircuitNumber=GetEmptyStringForNull(i.CircuitNumber)
                New.Station=i.Station
                New.Rotation=i.Rotation
                New.TagNumber=i.GetNearestTagNumber()
                New.save()
                #Now, split up any PrimaryLine and SecondaryLine Symbologies affected by this point
                PrimaryLineSymbologies=SymbologyPrimaryLine.objects.filter(Span=protectedspan.Span).filter(CircuitNumber=New.CircuitNumber)
                for primaryLineSymbology in PrimaryLineSymbologies:
                    NewLines=SplitLine(primaryLineSymbology.Line, New.Point)
                    for newLine in NewLines:
                        primaryLineSymbology.CreateCopy(newLine)
                    primaryLineSymbology.delete()
                SecondaryLineSymbologies=SymbologySecondaryLine.objects.filter(Span=protectedspan.Span).filter(CircuitNumber=New.CircuitNumber)
                for secondaryLineSymbology in SecondaryLineSymbologies:
                    NewLines=SplitLine(secondaryLineSymbology.Line, New.Point)
                    for newLine in NewLines:
                        secondaryLineSymbology.CreateCopy(newLine)
                    secondaryLineSymbology.delete()




    
class SymbologyRegulator(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Rotation=models.FloatField(db_column='rotation')
    PhaseCode=models.TextField(db_column='phasecode')
    CompatibleUnit=models.TextField(db_column='compatibleunit') 
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    TagNumber=models.TextField(db_column='tagnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyregulator'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        if(station):
            SymbologyRegulator.objects.filter(Station=station).delete()
            Regulators=compatibleunit.Assembly.objects.filter(CompatibleUnit__RegulatorIndicator=True, Station=station).exclude(
                           InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologyRegulator.objects.all().delete()
            Regulators=compatibleunit.Assembly.objects.filter(CompatibleUnit__RegulatorIndicator=True).exclude(
                           InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in Regulators:
            New=SymbologyRegulator()
            New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
            New.PhaseCode=i.GetPhaseCode()
            New.CompatibleUnit=str(i.CompatibleUnit)
            New.CircuitNumber=i.CircuitNumber
            New.Rotation=i.Rotation
            New.Station=i.Station
            New.TagNumber=i.GetNearestTagNumber()
            New.save()

class SymbologySpanGuy(models.Model):
    Line=models.LineStringField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    CompatibleUnit=models.TextField(db_column='compatibleunit')
    Span=models.ForeignKey('Span', db_column='span_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyspanguy'
        app_label='djangoproject'
    def BuildSymbology(self, span=None):
        if(span):
            SymbologySpanGuy.objects.filter(Span=span).delete()
            SpanGuys=compatibleunit.Assembly.objects.filter(CompatibleUnit__SpanGuyIndicator=True, Span=span).exclude(
                         InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologySpanGuy.objects.all().delete()
            SpanGuys=compatibleunit.Assembly.objects.filter(CompatibleUnit__SpanGuyIndicator=True).exclude(
                         InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in SpanGuys:
            New=SymbologySpanGuy()
            New.Line=SymbologyAdjustLine(i.Span.Line, i.CircuitNumber)
            New.CompatibleUnit=GetEmptyStringForNull(str(i.CompatibleUnit))
            New.Span=i.Span
            New.save()
            
class SymbologySubstation(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Name=models.TextField(db_column='name')
    Description=models.TextField(db_column='description', null=True, blank=True)
    Number=models.TextField(db_column='number')
    OMSNumber=models.TextField(db_column='omsnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologysubstation'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        if(station):
            SymbologySubstation.objects.filter(Station=station).delete()
            Substations=compatibleunit.Assembly.objects.filter(Station=station).filter(CompatibleUnit__SubstationIndicator=True).exclude(
                            InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologySubstation.objects.all().delete()
            Substations=compatibleunit.Assembly.objects.filter(CompatibleUnit__SubstationIndicator=True).exclude(
                            InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in Substations:
            New=SymbologySubstation()
            New.Point=i.Station.Point
            New.Name=i.SubstationName
            New.Station=i.Station
            New.Number=i.TagNumber
            try:
                New.OMSNumber=oms.OMSSubstationMap.objects.filter(GISSubstationNumber=i.TagNumber)[0].OMSSubstationNumber
            except IndexError:
                New.OMSNumber=''
            New.save()

class SymbologySwitch(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    CompatibleUnit=models.TextField(db_column='compatibleunit')
    OpenIndicator=models.BooleanField(db_column='openindicator')
    PhaseCode=models.TextField(db_column='phasecode')
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    Assembly=models.ForeignKey('Assembly', db_column='assembly_id')
    TagNumber=models.TextField(db_column='tagnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyswitch'
        app_label='djangoproject'
    def GetSwitchPhaseCodes(self, station):  #Temporary Code until OMS Upgrade in Spring, 2012, Gregory Roby 1/31/2012, handles multiple single phase reclosers as a single location
        Switches=compatibleunit.Assembly.objects.filter(Station=station).filter(CompatibleUnit__SwitchIndicator=True).exclude(
                      InstallStatus__Name='Install').exclude(BypassIndicator=True)
        TempPhaseCode=[]
        for i in Switches:
            TempPhaseCode.append(i.GetPhaseCode())
        TempPhaseCodeString=''.join(TempPhaseCode)
        PhaseCodeString=''
        if('A' in TempPhaseCodeString):
            PhaseCodeString=PhaseCodeString + 'A'
        if('B' in TempPhaseCodeString):
            PhaseCodeString=PhaseCodeString + 'B'
        if('C' in TempPhaseCodeString):
            PhaseCodeString=PhaseCodeString + 'C'
        return PhaseCodeString



    def BuildSymbology(self, station=None):
        if(station):
            SymbologySwitch.objects.filter(Station=station).delete()
            Switches=compatibleunit.Assembly.objects.filter(CompatibleUnit__SwitchIndicator=True, Station=station).exclude(
                         InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologySwitch.objects.all().delete()
            Switches=compatibleunit.Assembly.objects.filter(CompatibleUnit__SwitchIndicator=True).exclude(
                         InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in Switches:
            ProtectedSpans=compatibleunit.ProtectingAssembly.objects.filter(Assembly=i)
            if(not ProtectedSpans):
                New=SymbologySwitch()
                New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
                #New.PhaseCode=i.GetPhaseCode()
                New.PhaseCode=self.GetSwitchPhaseCodes(i.Station)  #Gets all phase codes for switches at the current station (keep until OMS upgrade 01/31/2012 Gregory Roby) 
                New.CompatibleUnit=str(i.CompatibleUnit)
                New.CircuitNumber=i.CircuitNumber
                New.Rotation=i.Rotation
                New.OpenIndicator=i.OpenIndicator
                New.Station=i.Station
                New.Assembly=i
                New.TagNumber=i.GetNearestTagNumber()
                New.save()
            for protectedSpan in ProtectedSpans:  #for each protected span, put a copy of the symbologyswitch 10% down that span
                New=SymbologySwitch()
                Point1=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
                Point2=SymbologyAdjustPoint(protectedSpan.Span.FarStation(i.Station).Point, i.CircuitNumber)
                New.Point=CalculateInBetweenPoint(Point1, Point2)
                #New.PhaseCode=i.GetPhaseCode()
                New.PhaseCode=self.GetSwitchPhaseCodes(i.Station)  #Gets all phase codes for switches at the current station (keep until OMS upgrade 01/31/2012 Gregory Roby) 
                New.CompatibleUnit=str(i.CompatibleUnit)
                New.CircuitNumber=i.CircuitNumber
                New.OpenIndicator=i.OpenIndicator
                New.Station=i.Station
                New.TagNumber=i.GetNearestTagNumber()
                New.Assembly=i
                New.save()
                #Now, split up any PrimaryLine and SecondaryLine Symbologies affected by this point
                PrimaryLineSymbologies=SymbologyPrimaryLine.objects.filter(Span=protectedSpan.Span).filter(CircuitNumber=New.CircuitNumber)
                for primaryLineSymbology in PrimaryLineSymbologies:
                    NewLines=SplitLine(primaryLineSymbology.Line, New.Point)
                    for newLine in NewLines:
                        primaryLineSymbology.CreateCopy(newLine)
                    primaryLineSymbology.delete()
                SecondaryLineSymbologies=SymbologySecondaryLine.objects.filter(Span=protectedSpan.Span).filter(CircuitNumber=New.CircuitNumber)
                for secondaryLineSymbology in SecondaryLineSymbologies:
                    NewLines=SplitLine(secondaryLineSymbology.Line, New.Point)
                    for newLine in NewLines:
                        secondaryLineSymbology.CreateCopy(newLine)
                    secondaryLineSymbology.delete()
            
class SymbologyURDMarker(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Rotation=models.FloatField(db_column='rotation')
    PhaseCode=models.TextField(db_column='phasecode')
    CompatibleUnit=models.TextField(db_column='compatibleunit') 
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyurdmarker'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        if(station):
            SymbologyURDMarker.objects.filter(Station=station).delete()
            URDMarkers=compatibleunit.Assembly.objects.filter(CompatibleUnit__URDMarkerIndicator=True, Station=station).exclude(
                           InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologyURDMarker.objects.all().delete()
            URDMarkers=compatibleunit.Assembly.objects.filter(CompatibleUnit__URDMarkerIndicator=True).exclude(
                           InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in URDMarkers:
            New=SymbologyURDMarker()
            New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
            New.PhaseCode=i.GetPhaseCode()
            New.CompatibleUnit=str(i.CompatibleUnit)
            New.CircuitNumber=i.CircuitNumber
            New.Rotation=i.Rotation
            New.Station=i.Station
            New.save()

class SymbologyVault(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Rotation=models.FloatField(db_column='rotation')
    PhaseCode=models.TextField(db_column='phasecode')
    CompatibleUnit=models.TextField(db_column='compatibleunit') 
    CircuitNumber=models.IntegerField(db_column='circuitnumber')
    Station=models.ForeignKey('Station', db_column='station_id')
    TagNumber=models.CharField(max_length=250, db_column='tagnumber')
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyvault'
        app_label='djangoproject'
    def BuildSymbology(self, station=None):
        if(station):
            SymbologyVault.objects.filter(Station=station).delete()
            Vaults=compatibleunit.Assembly.objects.filter(CompatibleUnit__VaultIndicator=True, Station=station).exclude(
                       InstallStatus__Name='Install').exclude(BypassIndicator=True)
        else:
            SymbologyVault.objects.all().delete()
            Vaults=compatibleunit.Assembly.objects.filter(CompatibleUnit__VaultIndicator=True).exclude(
                       InstallStatus__Name='Install').exclude(BypassIndicator=True)
        for i in Vaults:
            New=SymbologyVault()
            New.Point=SymbologyAdjustPoint(i.Station.Point, i.CircuitNumber)
            New.PhaseCode=i.GetPhaseCode()
            New.CompatibleUnit=str(i.CompatibleUnit)
            New.CircuitNumber=i.CircuitNumber
            New.Rotation=i.Rotation
            New.Station=i.Station
            New.TagNumber=GetEmptyStringForNull(i.TagNumber)
            New.save()
            


class SymbologyRadioLink(models.Model):
    StartRadioStation=models.ForeignKey('SymbologyRadioStation', related_name="RadioStartStation", on_delete=models.PROTECT)
    EndRadioStation=models.ForeignKey('SymbologyRadioStation', related_name="RadioEndStation", on_delete=models.PROTECT)
    Line=models.LineStringField(db_column='the_geom', null=True, blank=True, srid=djangoproject.settings.COOPGISSRID)
    SymbologyText=models.TextField(db_column='symbologytext', null=True, blank=True)
    SpanningTreeProtocolPriority=models.IntegerField(db_column='spanningtreeprotocolpriority', null=True, blank=True)
    Frequency=models.FloatField(db_column='frequency', null=True, blank=True)
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgissymbologyradiolink'
        app_label='djangoproject'
    def BuildGeometry(self):
        if self.StartRadioStation and self.EndRadioStation:
            Start=self.StartRadioStation.Point
            End=self.EndRadioStation.Point
            self.Line=LineString([Start, End])
            self.save()
    


class SymbologyRadioStation(models.Model):
    Point=models.PointField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    RadioModel=models.TextField(db_column='radiomodel', null=True, blank=True)
    AntennaModel=models.TextField(db_column='antennamodel', null=True, blank=True)
    Shielding=models.NullBooleanField(db_column='shielding', null=True, blank=True)
    DishRadius=models.TextField(db_column='dishradius', null=True, blank=True)
    Name=models.TextField(db_column='name')
    class Meta:
        db_table=u'coopgissymbologyradiostation'
        app_label='djangoproject'





